package com.qwc.blog.security.aop;

import com.qwc.blog.security.constant.SecurityConstant;
import com.qwc.blog.security.properties.SecurityProperties;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author qwc
 * @Date 2021/10/23 15:54
 */
@Component
@Aspect
public class RenewTokenAdvice {

    @Autowired
    private ServletRequest request;

    @Autowired
    private SecurityProperties securityProperties;

    @Pointcut("execution(* com.qwc.blog.controller.back.*Controller.*(..))")
    public void point() {
    }

    @Pointcut("execution(* com.qwc.blog.security.controller.LoginController.getProfile(..))")
    public void profile() {
    }

    @Around(value = "point()||profile()")
    public Object renewToken(ProceedingJoinPoint joinPoint) throws Throwable {
        Object proceed = joinPoint.proceed();
        if (!(proceed instanceof ResponseEntity)) {
            return proceed;
        }
        ResponseEntity<Map<String, Object>> responseEntity = (ResponseEntity<Map<String, Object>>) proceed;
        if (Objects.nonNull(request.getAttribute(SecurityConstant.RENEW_TOKEN))) {
            String token = securityProperties.getTokenStartWith() + request.getAttribute(SecurityConstant.RENEW_TOKEN);
            if (responseEntity.hasBody()) {
                responseEntity.getBody().put(SecurityConstant.RENEW_TOKEN, token);
            } else {
                Map<String, Object> map = new HashMap<>(16);
                map.put(SecurityConstant.RENEW_TOKEN, token);
                responseEntity = ResponseEntity.ok(map);
            }
        }
        return responseEntity;
    }
}
